<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 统计卡片 -->
        <div class="statistics-cards" style="margin-bottom: 20px;">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #409eff;">
                                <el-icon><List /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ statistics.totalConditions || 0 }}</div>
                                <div class="stat-label">总条件数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #67c23a;">
                                <el-icon><Check /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ statistics.completedConditions || 0 }}</div>
                                <div class="stat-label">已完成</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #e6a23c;">
                                <el-icon><Clock /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ statistics.pendingConditions || 0 }}</div>
                                <div class="stat-label">待完成</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #f56c6c;">
                                <el-icon><Star /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ statistics.upgradedUsers || 0 }}</div>
                                <div class="stat-label">已升级用户</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 表格顶部菜单 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('linkage.upgrade.condition.quick Search Fields') })"
        >
            <template #buttonsLeft>
                <el-button type="primary" @click="exportData">
                    <el-icon><Download /></el-icon>
                    导出数据
                </el-button>
                <el-button type="success" @click="batchCheck">
                    <el-icon><Check /></el-icon>
                    批量检查
                </el-button>
            </template>
        </TableHeader>

        <!-- 表格 -->
        <Table ref="tableRef"></Table>

        <!-- 表单 -->
        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { List, Check, Clock, Star, Download } from '@element-plus/icons-vue'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'

defineOptions({
    name: 'linkage/upgrade/condition',
})

const { t } = useI18n()
const tableRef = ref()
const statistics = reactive({
    totalConditions: 0,
    completedConditions: 0,
    pendingConditions: 0,
    upgradedUsers: 0
})

// 自定义操作按钮
const optButtons: OptButton[] = [
    ...defaultOptButtons(['edit', 'delete']),
    // {
    //     render: 'tipButton',
    //     name: 'check',
    //     title: '检查条件',
    //     text: '',
    //     type: 'success',
    //     icon: 'fa fa-check',
    //     click: (row: any) => {
    //         checkCondition(row.id)
    //     }
    // },
    // {
    //     render: 'tipButton',
    //     name: 'upgrade',
    //     title: '手动升级',
    //     text: '',
    //     type: 'warning',
    //     icon: 'fa fa-star',
    //     click: (row: any) => {
    //         manualUpgrade(row.user_id)
    //     }
    // }
]

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/linkage.upgrade.Condition/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { 
                label: '用户信息', 
                prop: 'user.nickname', 
                align: 'center', 
                width: 200
            },
            {   
                label: '条件类型', 
                prop: 'condition_type', 
                align: 'center', 
                width: 120,
                render: 'tag',
                replaceValue: { '1': '订单支付', '2': '邀请人数' },
                custom: { '1': 'success', '2': 'warning' }
            },
            { 
                label: '目标用户', 
                prop: 'targetUser.nickname', 
                align: 'center', 
                width: 200
            },
            { 
                label: '当前进度', 
                prop: 'current_count', 
                align: 'center', 
                width: 100
            },
            { 
                label: '目标数量', 
                prop: 'target_count', 
                align: 'center', 
                width: 100
            },
            { 
                label: '完成状态', 
                prop: 'is_completed', 
                align: 'center', 
                width: 100,
                render: 'tag',
                replaceValue: { '1': '已完成', '0': '未完成' },
                custom: { '1': 'success', '0': 'info' }
            },
            { 
                label: '完成时间', 
                prop: 'complete_time', 
                align: 'center', 
                render: 'datetime', 
                operator: 'RANGE', 
                sortable: 'custom', 
                width: 160, 
                timeFormat: 'yyyy-mm-dd hh:MM:ss' 
            },
            { 
                label: '创建时间', 
                prop: 'create_time', 
                align: 'center', 
                render: 'datetime', 
                operator: 'RANGE', 
                sortable: 'custom', 
                width: 160, 
                timeFormat: 'yyyy-mm-dd hh:MM:ss' 
            },
            { label: t('Operate'), align: 'center', width: 150, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: { condition_type: 1, target_count: 1, current_count: 0, is_completed: 0 },
    }
)

provide('baTable', baTable)

// 获取统计数据
const getStatistics = async () => {
    try {
        // 直接调用 API 获取数据，而不是通过 baTable.onTableHeaderAction
        const response: any = await baTable.api.index(baTable.table.filter)
        if (response && response.data) {
            const data = response.data
            
            // 使用 Object.assign 确保响应式更新
            Object.assign(statistics, {
                totalConditions: data.totalConditions || 0,
                completedConditions: data.completedConditions || 0,
                pendingConditions: data.pendingConditions || 0,
                upgradedUsers: data.upgradedUsers || 0
            });
        }
    } catch (error) {
        console.error('获取统计数据失败:', error)
    }
}

// 导出数据
const exportData = () => {
    ElMessage.success('导出功能开发中...')
}

// 批量检查
const batchCheck = async () => {
    try {
        ElMessage.info('批量检查功能开发中...')
        // 这里应该调用后端API进行批量检查
        // await fetch('/admin/linkage.UpgradeCondition/batchCheck', { method: 'POST' })
    } catch (error) {
        ElMessage.error('批量检查失败')
    }
}

// 检查单个条件
const checkCondition = async (conditionId: number) => {
    try {
        // 这里应该调用后端API检查条件
        // await fetch(`/admin/linkage.UpgradeCondition/check/${conditionId}`, { method: 'POST' })
        ElMessage.success('条件检查完成')
        baTable.onTableHeaderAction('refresh')
    } catch (error) {
        ElMessage.error('条件检查失败')
    }
}

// 手动升级用户
const manualUpgrade = async (userId: number) => {
    try {
        // 这里应该调用后端API手动升级用户
        // await fetch(`/admin/linkage.UpgradeCondition/manualUpgrade/${userId}`, { method: 'POST' })
        ElMessage.success('用户升级成功')
        baTable.onTableHeaderAction('refresh')
    } catch (error) {
        ElMessage.error('用户升级失败')
    }
}

onMounted(async () => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    
    // 先等待表格数据加载完成
    await baTable.getIndex()
    
    // 然后初始化排序和拖拽
    baTable.initSort()
    baTable.dragSort()
    
    // 最后获取统计数据（避免重复请求）
    await getStatistics()
})
</script>

<style scoped lang="scss">
.statistics-cards {
    .stat-card {
        .stat-content {
            display: flex;
            align-items: center;
            gap: 16px;
            
            .stat-icon {
                width: 48px;
                height: 48px;
                border-radius: 8px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                font-size: 20px;
            }
            
            .stat-info {
                flex: 1;
                
                .stat-number {
                    font-size: 24px;
                    font-weight: bold;
                    color: #303133;
                    line-height: 1;
                }
                
                .stat-label {
                    font-size: 14px;
                    color: #909399;
                    margin-top: 4px;
                }
            }
        }
    }
}
</style>
